package com.example.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.course.bean.Courses;
import com.example.course.bean.Student;
import com.example.course.bean.StudentCourse;
import com.example.course.bean.Teacher;
import com.example.course.converter.CourseConverter;
import com.example.course.dto.CourseDTO;
import com.example.course.dto.CourseQueryDTO;
import com.example.course.mapper.CoursesMapper;
import com.example.course.mapper.StudentMapper;
import com.example.course.mapper.TeacherMapper;
import com.example.course.service.CoursesService;
import com.example.course.service.StudentCourseService;
import com.example.course.vo.CourseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author Jasmine-drs
 * @description 针对表【courses(课程表)】的数据库操作Service实现
 * @createDate 2025-04-22 15:36:40
 */
@Slf4j
@Service
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses>
        implements CoursesService {

    private final CourseConverter courseConverter;
    private final StudentCourseService studentCourseService;
    private final TeacherMapper teacherMapper;
    private final StudentMapper studentMapper;

    public CoursesServiceImpl(CourseConverter courseConverter,
                              StudentCourseService studentCourseService,
                              TeacherMapper teacherMapper,
                              StudentMapper studentMapper) {
        this.courseConverter = courseConverter;
        this.studentCourseService = studentCourseService;
        this.teacherMapper = teacherMapper;
        this.studentMapper = studentMapper;
    }

    @Override
    public Page<CourseVO> getCourseList(CourseQueryDTO queryDTO) {
        Page<Courses> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Courses> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(queryDTO.getName())) {
            queryWrapper.like(Courses::getName, queryDTO.getName());
        }
        if (StringUtils.hasText(queryDTO.getCourseNum())) {
            queryWrapper.like(Courses::getCourseNum, queryDTO.getCourseNum());
        }
        if (queryDTO.getTeacherId() != null) {
            queryWrapper.eq(Courses::getTeacherId, queryDTO.getTeacherId());
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Courses::getCreateTime);

        // 查询数据库
        page = this.page(page, queryWrapper);

        // 转换为VO
        List<CourseVO> voList = courseConverter.toVOList(page.getRecords());

        // 构建返回结果
        Page<CourseVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(voList);

        return resultPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseVO addCourse(CourseDTO courseDTO) {
        // 检查课程代码是否已存在
        LambdaQueryWrapper<Courses> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Courses::getCourseNum, courseDTO.getCourseNum());
        if (this.count(queryWrapper) > 0) {
            throw new IllegalArgumentException("课程代码已存在，请使用其他课程代码");
        }

        // 检查教师是否存在
        Teacher teacher = teacherMapper.selectById(courseDTO.getTeacherId());
        if (teacher == null) {
            throw new IllegalArgumentException("教师不存在，请选择正确的教师");
        }

        // 将DTO转换为实体
        Courses course = courseConverter.toEntity(courseDTO);

        // 保存到数据库
        if (!this.save(course)) {
            throw new IllegalStateException("添加课程失败");
        }

        // 转换为VO并返回
        return courseConverter.toVO(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseVO updateCourse(Integer id, CourseDTO courseDTO) {
        // 检查课程是否存在
        Courses existingCourse = this.getById(id);
        if (existingCourse == null) {
            throw new IllegalArgumentException("课程不存在");
        }

        // 检查课程代码是否已被其他课程使用
        LambdaQueryWrapper<Courses> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Courses::getCourseNum, courseDTO.getCourseNum())
                .ne(Courses::getId, id);
        if (this.count(queryWrapper) > 0) {
            throw new IllegalArgumentException("课程代码已被其他课程使用，请使用其他课程代码");
        }

        // 检查教师是否存在
        Teacher teacher = teacherMapper.selectById(courseDTO.getTeacherId());
        if (teacher == null) {
            throw new IllegalArgumentException("教师不存在，请选择正确的教师");
        }

        // 将DTO转换为实体
        Courses course = courseConverter.toEntity(courseDTO);
        course.setId(id);
        course.setCreateTime(existingCourse.getCreateTime());
        course.setUpdateTime(new Date());

        // 更新数据库
        if (!this.updateById(course)) {
            throw new IllegalStateException("更新课程失败");
        }

        // 转换为VO并返回
        return courseConverter.toVO(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCourse(Integer id) {
        // 检查课程是否存在
        if (!this.lambdaQuery().eq(Courses::getId, id).exists()) {
            throw new IllegalArgumentException("课程不存在");
        }

        // 删除学生-课程关联
        LambdaQueryWrapper<StudentCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentCourse::getCourseId, id);
        studentCourseService.remove(queryWrapper);

        // 删除课程
        return this.removeById(id);
    }

    @Override
    public CourseVO getCourseById(Integer id) {
        // 查询课程
        Courses course = this.getById(id);
        if (course == null) {
            throw new IllegalArgumentException("课程不存在");
        }

        // 转换为VO并返回
        return courseConverter.toVO(course);
    }

    @Override
    public boolean isTeacher(Integer userId) {
        if (userId == null) {
            return false;
        }

        // 检查是否为教师
        Teacher teacher = teacherMapper.selectById(userId);
        if (teacher != null) {
            return true;
        }

        // 检查是否为学生
        Student student = studentMapper.selectById(userId);
        return student == null; // 不是学生也不是教师，返回false
    }
}




